const Router = require('koa-router')
const router = new Router()
const callCloudDB = require('../utils/callCloudDB.js')
const cloudStorage = require('../utils/cloudStorage.js')
// 获取列表

router.get('/list', async (ctx) => {

    // 默认http api获取10条数据
    const query = `db.collection('goods').get()`
    const res = await callCloudDB(ctx, 'databasequery', query)
    let fileList = []
    const data = res.data
    for (let i = 0, len = data.length; i < len; i++) {
        fileList.push({
            fileid: JSON.parse(data[i]).imgUrl,
            max_age: 7200
        })
    }
    //下载结果处理
    const dlRes = await cloudStorage.download(ctx, fileList)
    let returnData = []
    for (let i = 0, len = dlRes.file_list.length; i < len; i++) {
        returnData.push({
            download_url: dlRes.file_list[i].download_url,
            fileid: dlRes.file_list[i].fileid,
            _id: JSON.parse(data[i])._id,
            title: JSON.parse(data[i]).title,
            desc: JSON.parse(data[i]).desc,
            detail: JSON.parse(data[i]).detailUrl
        })
    }
    ctx.body = {
        code: 20000,
        data: returnData
    }
})
// 获取详情
router.get('/getById', async (ctx, next) => {
    const query = `db.collection('goods').doc('${ctx.request.query.id}').get()`
    const res = await callCloudDB(ctx, 'databasequery', query)
    ctx.body = {
        code: 20000,
        data: JSON.parse(res.data)
    }
})
// 更新
router.post("/updatelist", async (ctx, next) => {
    const params = ctx.request.body;
    const query = `
          db.collection('goods').doc('${params._id}').update({
              data: {
                  title: '${params.title}',
                  desc: '${params.desc}',
                  detailUrl: '${params.detailUrl}'
              }
          })
      `;
    const res = await callCloudDB(ctx, "databaseupdate", query);
    ctx.body = {
      code: 20000,
      data: res,
    };
  });
//删除操作
router.get("/del", async (ctx, next) => {
    const params = ctx.request.query;
    const query = `db.collection('goods').doc('${params.id}').remove()`;
    const res = await callCloudDB(ctx, "databasedelete", query);
    ctx.body = {
        code: 20000,
        data: res,
    };
});



module.exports = router